package com.sh.d1.gatewayserver.router;

import com.sh.d1.gameserver.async.AsyncOperationProcessor;
import com.sh.d1.gatewayserver.GameServerFinder;
import com.sh.d1.gatewayserver.NettyClient;
import com.sh.d1.gatewayserver.NettyClientGroup;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.util.AttributeKey;

class GameMsgHandler {
    public void sendMsg(ChannelHandlerContext ctx, BinaryWebSocketFrame outputFrame) {
        if (null == ctx || null == outputFrame) {
            return;
        }

        AsyncOperationProcessor.getInstance().process(()->{
            NettyClient nettyClient = null;

            //获取游戏服务器id
            AttributeKey<String> attrKey = AttributeKey.valueOf("gameserverId");

            String gameServerId = ctx.channel().attr(attrKey).get();

            if (null != gameServerId) {
                nettyClient = NettyClientGroup.getByServerId(gameServerId);
            }

            if(null == nettyClient){
                nettyClient=GameServerFinder.selectOnGameServer(GameServerFinder.JOB_TYEP_GAME);

            }
            if (null == nettyClient) {
                return;
            }
            if(!nettyClient.getTargetServerId().equals(gameServerId)){
                ctx.channel().attr(attrKey).setIfAbsent(nettyClient.getTargetServerId());
            }
            nettyClient.sendMsg(outputFrame);
        });

    }
}
